

import React, { useState, useEffect, useCallback } from 'react';
import { Link, useNavigate, useLocation } from 'react-router-dom';
import styles from './styles.module.css';
import authApi, { LoginParams } from '../../api/auth';

interface LoginFormData {
  username: string;
  password: string;
  captcha: string;
  rememberPassword: boolean;
}

const LoginPage: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  
  // 状态管理
  const [showPassword, setShowPassword] = useState(false);
  const [loading, setLoading] = useState(false);
  const [captchaUrl, setCaptchaUrl] = useState('');
  
  // 表单数据
  const [loginInfo, setLoginInfo] = useState<LoginFormData>({
    username: '',
    password: '',
    captcha: '',
    rememberPassword: true
  });

  // 初始化验证码
  const initCaptcha = useCallback(() => {
    setCaptchaUrl(authApi.getCaptcha());
  }, []);

  // 设置页面标题和初始化
  useEffect(() => {
    const originalTitle = document.title;
    document.title = '登录 - 继续教育学院';
    
    // 初始化验证码
    initCaptcha();
    
    // 加载记住的密码
    const localLoginInfo = localStorage.getItem('loginInfo');
    if (localLoginInfo) {
      try {
        const savedInfo = JSON.parse(localLoginInfo);
        setLoginInfo(prev => ({
          ...prev,
          username: savedInfo.username || '',
          password: savedInfo.password || '',
        }));
      } catch (error) {
        console.error('解析保存的登录信息失败:', error);
      }
    }
    
    return () => { document.title = originalTitle; };
  }, [initCaptcha]);

  // 跳转到注册页面
  const goToRegister = () => {
    navigate('/register');
  };

  // 处理密码显示切换
  const handlePasswordToggle = () => {
    setShowPassword(!showPassword);
  };

  // 主要登录处理函数
  const handleLogin = async (isQuick: boolean = false) => {
    const { username, password, captcha } = loginInfo;
    
    if (!username || !password) {
      alert('请输入用户名和密码');
      return;
    }
    
    if (!isQuick && !captcha) {
      alert('请输入验证码');
      return;
    }
    
    try {
      setLoading(true);
      
      const loginParams: LoginParams = {
        username,
        password: password.toString(),
        captcha,
        isQuick
      };
      
      const response = await authApi.login(loginParams);
      
      // 保存记住密码状态
      if (loginInfo.rememberPassword) {
        localStorage.setItem('loginInfo', JSON.stringify({ username, password }));
      } else {
        localStorage.removeItem('loginInfo');
      }
      
      // 登录成功处理
      onLoginSuccess(response.data);
    } catch (error: any) {
      // 10003为验证码错误专属业务码
      if (error.code === 10003) {
        // 为防止爆破，验证码错误则刷新验证码
        initCaptcha();
        // 清空验证码输入框
        setLoginInfo(prev => ({ ...prev, captcha: '' }));
        alert('验证码错误，请重新输入');
      } else {
        alert(error.message || '登录失败，请重试');
      }
    } finally {
      setLoading(false);
    }
  };

  // 登录成功处理
  const onLoginSuccess = async (data: any = {}) => {
    try {
      console.log('=== 登录成功处理 ===');
      console.log('登录响应数据:', data);
      
      // 保存token (后端返回的是accessToken字段)
      if (data && data.accessToken) {
        localStorage.setItem('token', data.accessToken);
        console.log('Token已保存:', data.accessToken);
      }
      
      // 登录响应中不包含用户信息，需要调用API获取
      try {
        console.log('正在获取用户信息...');
        const userInfoResponse = await authApi.getUser();
        console.log('用户信息响应:', userInfoResponse);
        
        if (userInfoResponse && userInfoResponse.data) {
          localStorage.setItem('userInfo', JSON.stringify(userInfoResponse.data));
          console.log('用户信息已保存:', userInfoResponse.data);
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
      }
      
      // 跳转处理
      const searchParams = new URLSearchParams(location.search);
      const redirect = searchParams.get('redirect');
      
      console.log('准备跳转到:', redirect || '/home');
      
      if (redirect) {
        navigate(redirect);
      } else {
        navigate('/home');
      }
    } catch (error) {
      console.error('登录成功处理失败:', error);
      navigate('/home');
    }
  };

  // 处理表单提交
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    handleLogin();
  };

  return (
    <div className={styles.pageWrapper}>
      <div className="min-h-screen flex flex-col justify-center bg-gray-50 bg-cover bg-center" 
           style={{ backgroundImage: 'url()' }}>
        
        <div className="max-w-md w-full mx-auto bg-white bg-opacity-20 backdrop-blur-sm rounded-lg shadow-lg p-8 m-4">
          <div className="text-center mb-8">
            <div className="flex items-center justify-center mb-4">
              <div className="w-12 h-12 bg-blue-600 rounded-lg flex items-center justify-center mr-3">
                <i className="fas fa-graduation-cap text-white text-xl"></i>
              </div>
              <h2 className="text-2xl font-normal text-gray-600">继续教育学院</h2>
            </div>
          </div>

          <form onSubmit={handleSubmit} className="space-y-5">
            {/* 用户名输入 */}
            <div>
              <div className="relative">
                <i className="fas fa-user absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                <input
                  type="text"
                  value={loginInfo.username}
                  onChange={(e) => setLoginInfo(prev => ({ ...prev, username: e.target.value }))}
                  className="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none"
                  placeholder="请输入用户名"
                  maxLength={20}
                  autoFocus
                  required
                />
              </div>
            </div>

            {/* 密码输入 */}
            <div>
              <div className="relative">
                <i className="fas fa-lock absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                <input
                  type={showPassword ? 'text' : 'password'}
                  value={loginInfo.password}
                  onChange={(e) => setLoginInfo(prev => ({ ...prev, password: e.target.value }))}
                  className="w-full pl-10 pr-12 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none"
                  placeholder="请输入密码"
                  maxLength={20}
                  required
                  onKeyDown={(e) => e.key === 'Enter' && handleLogin()}
                />
                <button
                  type="button"
                  onClick={handlePasswordToggle}
                  className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
                >
                  <i className={`fas ${showPassword ? 'fa-eye-slash' : 'fa-eye'}`}></i>
                </button>
              </div>
            </div>

            {/* 验证码输入 */}
            <div className="flex space-x-3">
              <div className="flex-1 relative">
                <i className="fas fa-key absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                <input
                  type="text"
                  value={loginInfo.captcha}
                  onChange={(e) => setLoginInfo(prev => ({ ...prev, captcha: e.target.value }))}
                  className="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none"
                  placeholder="请输入验证码"
                  maxLength={4}
                  onKeyDown={(e) => e.key === 'Enter' && handleLogin()}
                />
              </div>
              {captchaUrl && (
                <img
                  src={captchaUrl}
                  alt="验证码"
                  className="w-20 h-12 cursor-pointer border border-gray-300 rounded-lg"
                  onClick={initCaptcha}
                />
              )}
            </div>

            {/* 记住我 */}
            <div className="flex items-center">
              <input
                type="checkbox"
                id="remember"
                checked={loginInfo.rememberPassword}
                onChange={(e) => setLoginInfo(prev => ({ ...prev, rememberPassword: e.target.checked }))}
                className="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
              />
              <label htmlFor="remember" className="ml-2 text-sm text-gray-600">
                记住我
              </label>
            </div>

            {/* 登录按钮 */}
            <div className="flex space-x-4">
              <button
                type="button"
                onClick={goToRegister}
                className="flex-1 py-3 px-4 border border-blue-600 text-blue-600 rounded-lg font-medium hover:bg-blue-50 transition-colors"
              >
                注册
              </button>
              <button
                type="submit"
                disabled={loading}
                className="flex-1 py-3 px-4 bg-blue-600 text-white rounded-lg font-medium hover:bg-blue-700 transition-colors disabled:opacity-50"
              >
                {loading ? '登录中...' : '登录'}
              </button>
            </div>
          </form>
        </div>

        {/* 页脚 */}
        <div className="text-center py-3 text-gray-500 text-sm">
          <p>&copy; 2024 继续教育学院. 保留所有权利.</p>
        </div>
      </div>
    </div>
  );
};

export default LoginPage;

